package com.sudoku.listener;

import java.awt.Color;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import com.sudoku.common.Constants;
import com.sudoku.common.Utils;
import com.sudoku.ui.Sudoku;
import com.sudoku.ui.content.SPanel;

public class InputListener implements  DocumentListener {
	private Sudoku sudoku;
	private SPanel sPanel;
	private JTextField selectedCell;
	private int rowSelected, colSelected;
	
	public InputListener(Sudoku sudoku, SPanel sPanel, JTextField selectedCell, int row, int col) {
		this.sudoku = sudoku;
		this.sPanel = sPanel;
		this.selectedCell = selectedCell;
		rowSelected = row;
		colSelected = col;
	}
	
	private boolean isSelectedCorrect() {
		int answer = sPanel.getPuzzle()[rowSelected][colSelected];
		String text = sPanel.getTfCells()[rowSelected][colSelected].getText();
		
		if (text==null || "".equals(text) || !Utils.isInteger(text) || (answer!=Integer.parseInt(text))) {
			return false;
		} else {
			return true;
		}
	}
	
	private boolean checkGameOver() {
		for (int row = 0; row < Constants.GRID_SIZE; row++) {
			for (int col = 0; col < Constants.GRID_SIZE; col++) {
				if (sPanel.getMask()[row][col]) {
					String text = sPanel.getTfCells()[row][col].getText();
					if (!Utils.isInteger(text) || Integer.parseInt(text)!=sPanel.getPuzzle()[row][col]) {
						return false;
					}
				}
			}
		}
		return true;
	}
	
	@Override
	public void insertUpdate(DocumentEvent e) {
		
		if (!isSelectedCorrect()) {
			selectedCell.setBackground(Color.RED);
		} else {
			selectedCell.setBackground(Color.GREEN);
			sPanel.setFilledCellCnt();
			sPanel.getStatus().update();
			// 检查游戏是否结束
			if (checkGameOver()) {
				/**
				 * 锁定单元格，不允许再修改
				 */
				for (int row = 0; row<Constants.GRID_SIZE; row++) {
					for (int col = 0; col<Constants.GRID_SIZE; col++) {
						if (sPanel.getMask()[row][col]) {
							sPanel.getTfCells()[row][col].setEditable(false);
							sPanel.getTfCells()[row][col].setBackground(Color.GRAY);
						}
	
					}
				}
				
				JOptionPane.showMessageDialog(null, "Congratulation!");
			}
		}
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		if (!isSelectedCorrect()) {
			if (selectedCell.getText()==null || "".equals(selectedCell.getText())) {
				selectedCell.setBackground(Constants.OPEN_CELL_BGCOLOR);
				
			} else {
				selectedCell.setBackground(Color.RED);
			}
	
		} else {
			selectedCell.setBackground(Color.GREEN);
			sPanel.setFilledCellCnt();
			sPanel.getStatus().update();
			if (checkGameOver()) {
				JOptionPane.showMessageDialog(null, "Congratulation!");
			}
		}
	}
	
	@Override
	public void changedUpdate(DocumentEvent e) {
	}


}
